package spring.mvc.servlet;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.util.EntityUtils;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import spring.mvc.response.RequestWrapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 简单的 servlet 反向代理
 *
 * @author ME
 */
public class SimpleProxy extends ProxyServlet {

    @Override
    protected HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri, HttpServletRequest servletRequest) throws IOException {
        HttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        System.out.println("请求地址：" + proxyRequestUri);
        System.out.println("请求方法：" + method);
        RequestWrapper requestWrapper = new RequestWrapper(servletRequest);
        proxyRequest.setEntity(new InputStreamEntity(requestWrapper.getInputStream(), this.getContentLength(servletRequest)));
        return proxyRequest;
    }

    @Override
    protected HttpResponse doExecute(HttpServletRequest servletRequest, HttpServletResponse servletResponse, HttpRequest proxyRequest) throws IOException {
        HttpResponse response = super.doExecute(servletRequest, servletResponse, proxyRequest);

        // EntityUtils.toString + BufferedHttpEntity 实现多次读取
        BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
        System.out.println("响应内容：" + EntityUtils.toString(entity, StandardCharsets.UTF_8));
        System.out.println();
        // 把缓存过的 entity 放回 HttpResponse
        response.setEntity(entity);
        // 请求地址：http://idea.lanyus.com/jrebel/leases
        // 请求方法：POST
        // 请求头：
        // user-agent：		JRebel-Licensing/2021.4.2; Email:616468159@qq.com; Guid:vqVFsxX7uLbfhWWCuckey6MP4wVW8xYrq+ePtuTJYAA=
        // content-length：		550
        // content-type：		application/x-www-form-urlencoded; charset=UTF-8
        // host：		127.0.0.1:8080
        // connection：		Keep-Alive
        // accept-encoding：		gzip,deflate
        // 请求体：token=178C8C6D-0B31-7AE2-1D29-09FF5F1B4CCE&guid=vqVFsxX7uLbfhWWCuckey6MP4wVW8xYrq%2BePtuTJYAA%3D&clientTime=1639104751475&clientProtocolVersion=1.1&username=bin.yin&rebelVersion=2021.4.2&product=JRebel&definedUserId=616468159%40qq.com&signature=IJEqP0WXRC7RgmVrVwZE2wd7oFDtTKCCAPnf%2FyNAERNTJLYgcOupmXchAb0IcxU5lhD2hzWTqHYAu213G0O%2BAl0HPeMS7UQLUu2gNKJOcrHXVRhguz3ZI64FtQaHJpNSMk5GOMpC%2F47rbtY7%2FWZO%2FYhmUkTSYIE0jdpUcMad4Gc%3D&randomness=SzTdpm%2FCxwo%3D&oldDefinedUserId=616468159%40qq.com&oldGuid=vqVFsxX7uLbfhWWCuckey6MP4wVW8xYrq%2BePtuTJYAA%3D
        // 响应内容：{"serverVersion":"3.2.4","serverProtocolVersion":"1.1","serverGuid":"a1b4aea8-b031-4302-b602-670a990272cb","groupType":"managed","id":1,"licenseType":1,"evaluationLicense":false,"signature":"kA0R4ut5soOGHZlcJucZp9v1t1JP2u1+EkK5PF8EsFZlKHgYogem5vf9ezyGmceLpclsS/MuO1TeZ1EpBd7dO7tTh/mtVtikPTrsIrS0nyoCOPt4IlQF94XxKMgl725AkLimqHH2mFhWDya1vwx4KtW9ATUOHbgETffN0JlwXm8=","serverRandomness":"H2ulzLlh7E0=","seatPoolType":"standalone","statusCode":"SUCCESS","offline":false,"validFrom":null,"validUntil":null,"company":"ilanyu","orderId":"","zeroIds":[],"licenseValidFrom":1490544001000,"licenseValidUntil":1691839999000}
        //
        // 请求地址：http://idea.lanyus.com/agent/features
        // 请求方法：POST
        // 请求头：
        // user-agent：		JRebel-Licensing/2021.4.2; Email:616468159@qq.com; Guid:vqVFsxX7uLbfhWWCuckey6MP4wVW8xYrq+ePtuTJYAA=
        // content-length：		429
        // content-type：		application/x-www-form-urlencoded; charset=UTF-8
        // host：		127.0.0.1:8080
        // connection：		Keep-Alive
        // accept-encoding：		gzip,deflate
        // 请求体：token=178C8C6D-0B31-7AE2-1D29-09FF5F1B4CCE&guid=vqVFsxX7uLbfhWWCuckey6MP4wVW8xYrq%2BePtuTJYAA%3D&clientTime=1639104751577&clientProtocolVersion=1.1&username=bin.yin&rebelVersion=2021.4.2&product=JRebel&definedUserId=616468159%40qq.com&signature=0s3J%2BsdqgedUilHuBqJBOMm6dpj7GclaOog7nhGX3meXvIR2vAxUBvPW%2BZNxxOB0iLSEtMierVCvEnWKgml7zH2xiKppJTU7%2BvlRQAp8CHElC%2F5ThgqQAiks6JfR5tPpL7Bt59nJdvt3BcFEgO3nPWPZuYpkbOmQVtS%2F1mS03x8%3D
        // 响应内容：<!doctype html><html lang="en"><head><title>HTTP Status 404 – Not Found</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 404 – Not Found</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> &#47;agent&#47;features</p><p><b>Description</b> The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.</p><hr class="line" /><h3>Apache Tomcat/8.5.32</h3></body></html>
        //
        // 响应内容：<!doctype html><html lang="en"><head><title>HTTP Status 404 – Not Found</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 404 – Not Found</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> &#47;agent&#47;features</p><p><b>Description</b> The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.</p><hr class="line" /><h3>Apache Tomcat/8.5.32</h3></body></html>

        return response;
    }

    /**
     * 从请求头获取 Content-Length
     */
    private long getContentLength(HttpServletRequest request) {
        String contentLengthHeader = request.getHeader("Content-Length");
        return contentLengthHeader != null ? Long.parseLong(contentLengthHeader) : -1L;
    }

}
